const { ipcRenderer } = require('electron');
const path = require('path');
const fs = require('fs');

// 全局变量
let selectedFiles = [];
let isProcessing = false;
let processingStartTime = 0;

// DOM 元素
const elements = {
    selectFolder: document.getElementById('selectFolder'),
    selectFiles: document.getElementById('selectFiles'),
    dropZone: document.getElementById('dropZone'),
    fileList: document.getElementById('fileList'),
    fileCount: document.getElementById('fileCount'),
    fileCountDisplay: document.getElementById('fileCountDisplay'),
    clearAllFiles: document.getElementById('clearAllFiles'),
    quality: document.getElementById('quality'),
    qualityValue: document.getElementById('qualityValue'),
    compressionSettings: document.getElementById('compressionSettings'),
    width: document.getElementById('width'),
    height: document.getElementById('height'),
    maintainAspectRatio: document.getElementById('maintainAspectRatio'),
    // 裁剪相关元素
    enableCrop: document.getElementById('enableCrop'),
    cropSettings: document.getElementById('cropSettings'),
    customRatioSettings: document.getElementById('customRatioSettings'),
    cropPositionSettings: document.getElementById('cropPositionSettings'),
    cropLeft: document.getElementById('cropLeft'),
    cropTop: document.getElementById('cropTop'),
    cropWidth: document.getElementById('cropWidth'),
    cropHeight: document.getElementById('cropHeight'),
    processBtn: document.getElementById('processBtn'),
    progressSection: document.getElementById('progressSection'),
    progressText: document.getElementById('progressText'),
    progressPercent: document.getElementById('progressPercent'),
    progressFill: document.getElementById('progressFill'),
    completionModal: document.getElementById('completionModal'),
    completionMessage: document.getElementById('completionMessage'),
    replaceOriginalBtn: document.getElementById('replaceOriginalBtn'),
    viewResultsBtn: document.getElementById('viewResultsBtn'),
    minimizeApp: document.getElementById('minimizeApp'),
    maximizeApp: document.getElementById('maximizeApp'),
    closeApp: document.getElementById('closeApp')
};

// 获取选中的输出格式
function getSelectedOutputFormat() {
    const selectedRadio = document.querySelector('input[name="outputFormat"]:checked');
    return selectedRadio ? selectedRadio.value : '';
}

// 检查格式是否支持压缩
function formatSupportsCompression(format) {
    const compressibleFormats = ['jpeg', 'webp', 'tiff', 'png'];
    return compressibleFormats.includes(format.toLowerCase());
}

// 更新压缩设置显示
function updateCompressionSettings() {
    const selectedFormat = getSelectedOutputFormat();
    const shouldShowCompression = selectedFormat && formatSupportsCompression(selectedFormat);
    
    if (shouldShowCompression) {
        elements.compressionSettings.style.display = 'block';
    } else {
        elements.compressionSettings.style.display = 'none';
    }
}

// 更新裁剪设置显示
function updateCropSettings() {
    const isEnabled = elements.enableCrop.checked;
    
    if (isEnabled) {
        elements.cropSettings.style.display = 'block';
    } else {
        elements.cropSettings.style.display = 'none';
    }
}

// 更新自定义比例设置显示
function updateCustomRatioSettings() {
    const selectedRatio = getSelectedCropRatio();
    const isCustom = selectedRatio === 'custom';
    
    if (isCustom) {
        elements.customRatioSettings.style.display = 'block';
        elements.cropPositionSettings.style.display = 'none';
    } else {
        elements.customRatioSettings.style.display = 'none';
        elements.cropPositionSettings.style.display = 'block';
    }
}

// 获取选中的裁剪比例
function getSelectedCropRatio() {
    const selectedRadio = document.querySelector('input[name="cropRatio"]:checked');
    return selectedRadio ? selectedRadio.value : null;
}

// 获取选中的裁剪位置
function getSelectedCropPosition() {
    const selectedRadio = document.querySelector('input[name="cropPosition"]:checked');
    return selectedRadio ? selectedRadio.value : 'center';
}

// 获取裁剪选项
function getCropOptions() {
    if (!elements.enableCrop.checked) {
        return null;
    }
    
    const ratio = getSelectedCropRatio();
    const position = getSelectedCropPosition();
    
    const cropOptions = {
        ratio: ratio,
        position: position
    };
    
    // 如果是自定义裁剪，添加自定义参数
    if (ratio === 'custom') {
        const left = parseInt(elements.cropLeft.value) || 0;
        const top = parseInt(elements.cropTop.value) || 0;
        const width = parseInt(elements.cropWidth.value) || 0;
        const height = parseInt(elements.cropHeight.value) || 0;
        
        if (width > 0 && height > 0) {
            cropOptions.customCrop = {
                left: left,
                top: top,
                width: width,
                height: height
            };
        } else {
            return null; // 自定义裁剪参数无效
        }
    }
    
    return cropOptions;
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    initializeEventListeners();
    updateCompressionSettings(); // 初始化压缩设置显示状态
    updateUI();
});

// 初始化事件监听器
function initializeEventListeners() {
    // 文件选择
    elements.selectFolder.addEventListener('click', selectFolder);
    elements.selectFiles.addEventListener('click', selectFiles);
    
    // 拖拽功能
    elements.dropZone.addEventListener('dragover', handleDragOver);
    elements.dropZone.addEventListener('dragleave', handleDragLeave);
    elements.dropZone.addEventListener('drop', handleDrop);
    
    // 阻止按钮区域的拖拽事件冒泡
    const dropZoneButtons = elements.dropZone.querySelectorAll('.btn');
    dropZoneButtons.forEach(button => {
        button.addEventListener('dragover', (e) => e.stopPropagation());
        button.addEventListener('drop', (e) => e.stopPropagation());
    });
    
    // 格式选择监听
    const formatRadios = document.querySelectorAll('input[name="outputFormat"]');
    formatRadios.forEach(radio => {
        radio.addEventListener('change', updateCompressionSettings);
    });
    
    // 质量滑块
    elements.quality.addEventListener('input', (e) => {
        elements.qualityValue.textContent = e.target.value;
    });
    
    // 裁剪功能监听
    elements.enableCrop.addEventListener('change', updateCropSettings);
    
    // 裁剪比例选择监听
    const cropRatioRadios = document.querySelectorAll('input[name="cropRatio"]');
    cropRatioRadios.forEach(radio => {
        radio.addEventListener('change', updateCustomRatioSettings);
    });
    
    // 处理按钮
    elements.processBtn.addEventListener('click', startProcessing);
    
    // 完成提示框按钮事件
    elements.replaceOriginalBtn.addEventListener('click', replaceOriginalFiles);
    elements.viewResultsBtn.addEventListener('click', viewResults);
    
    // 清空所有文件按钮事件
    elements.clearAllFiles.addEventListener('click', clearAllFiles);
    
    // 窗口控制按钮事件
    elements.minimizeApp.addEventListener('click', async () => {
        await ipcRenderer.invoke('minimize-app');
    });
    
    elements.maximizeApp.addEventListener('click', async () => {
        await ipcRenderer.invoke('maximize-app');
    });
    
    elements.closeApp.addEventListener('click', async () => {
        await ipcRenderer.invoke('close-app');
    });
    
    // IPC 事件监听
    ipcRenderer.on('processing-progress', handleProcessingProgress);
}

// 选择文件夹
async function selectFolder() {
    try {
        const result = await ipcRenderer.invoke('select-folder');
        if (result && result.imageFiles.length > 0) {
            selectedFiles = result.imageFiles;
            updateFileList();
            updateUI();
        } else if (result && result.imageFiles.length === 0) {
            showNotification('所选文件夹中没有找到图片文件', 'warning');
        }
    } catch (error) {
        showNotification('选择文件夹失败: ' + error.message, 'error');
    }
}

// 选择文件
async function selectFiles() {
    try {
        const files = await ipcRenderer.invoke('select-files');
        if (files.length > 0) {
            selectedFiles = [...selectedFiles, ...files];
            removeDuplicateFiles();
            updateFileList();
            updateUI();
        }
    } catch (error) {
        showNotification('选择文件失败: ' + error.message, 'error');
    }
}



// 拖拽处理
function handleDragOver(e) {
    e.preventDefault();
    elements.dropZone.classList.add('drag-over');
}

function handleDragLeave(e) {
    e.preventDefault();
    elements.dropZone.classList.remove('drag-over');
}

function handleDrop(e) {
    e.preventDefault();
    elements.dropZone.classList.remove('drag-over');
    
    const files = Array.from(e.dataTransfer.files);
    const imageFiles = files.filter(file => {
        const ext = path.extname(file.path).toLowerCase();
        return ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp', '.svg', '.ico'].includes(ext);
    });
    
    if (imageFiles.length > 0) {
        selectedFiles = [...selectedFiles, ...imageFiles.map(file => file.path)];
        removeDuplicateFiles();
        updateFileList();
        updateUI();
    } else {
        showNotification('请拖拽图片文件', 'warning');
    }
}

// 移除重复文件
function removeDuplicateFiles() {
    selectedFiles = [...new Set(selectedFiles)];
}

// 更新文件列表显示
function updateFileList() {
    elements.fileList.innerHTML = '';
    
    selectedFiles.forEach((filePath, index) => {
        const fileName = path.basename(filePath);
        const fileSize = getFileSize(filePath);
        const fileExt = path.extname(filePath).toLowerCase();
        
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item fade-in';
        fileItem.innerHTML = `
            <div class="file-info">
                <span class="file-icon">${getFileIcon(fileExt)}</span>
                <div class="file-details">
                    <h4>${fileName}</h4>
                    <p>${fileSize} • ${fileExt.substring(1).toUpperCase()}</p>
                </div>
            </div>
            <button class="remove-file" onclick="removeFile(${index})" title="移除文件">
                ×
            </button>
        `;
        
        elements.fileList.appendChild(fileItem);
    });
    
    elements.fileCount.textContent = `(${selectedFiles.length})`;
}

// 移除文件
function removeFile(index) {
    selectedFiles.splice(index, 1);
    updateFileList();
    updateUI();
}

// 获取文件图标
function getFileIcon(ext) {
    const iconMap = {
        '.jpg': '🖼️', '.jpeg': '🖼️', '.png': '🖼️',
        '.gif': '🎞️', '.bmp': '🖼️', '.tiff': '🖼️',
        '.webp': '🖼️', '.svg': '🎨', '.ico': '🔷'
    };
    return iconMap[ext] || '📄';
}

// 获取文件大小
function getFileSize(filePath) {
    try {
        const stats = fs.statSync(filePath);
        return formatFileSize(stats.size);
    } catch (error) {
        return '未知大小';
    }
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 解析尺寸值，支持像素和百分比
function parseSizeValue(value) {
    if (!value || value.trim() === '') return null;
    
    const trimmedValue = value.trim();
    
    // 检查是否是百分比
    if (trimmedValue.endsWith('%')) {
        const percentValue = parseFloat(trimmedValue.slice(0, -1));
        if (isNaN(percentValue) || percentValue <= 0) {
            throw new Error('百分比值必须是大于0的数字');
        }
        return { type: 'percentage', value: percentValue };
    } else {
        // 处理像素值
        const pixelValue = parseInt(trimmedValue);
        if (isNaN(pixelValue) || pixelValue <= 0) {
            throw new Error('像素值必须是大于0的整数');
        }
        return { type: 'pixel', value: pixelValue };
    }
}

// 更新UI状态
function updateUI() {
    const hasFiles = selectedFiles.length > 0;
    
    elements.processBtn.disabled = !hasFiles || isProcessing;
    
    if (!hasFiles) {
        elements.processBtn.textContent = '请先选择图片文件';
    } else if (isProcessing) {
        elements.processBtn.textContent = '处理中...';
    } else {
        elements.processBtn.innerHTML = '<span class="icon">⚡</span>开始处理';
    }
}

// 开始处理
async function startProcessing() {
    if (isProcessing) return;
    
    try {
        isProcessing = true;
        processingStartTime = Date.now();
        updateUI();
        
        // 显示进度条
        elements.progressSection.style.display = 'block';
        
        // 获取处理选项
        const selectedFormat = getSelectedOutputFormat();
        const quality = parseInt(elements.quality.value);
        
        const options = {
            format: selectedFormat || null,
            // 只有在格式支持压缩且质量不是100%时才应用压缩
            quality: (selectedFormat && formatSupportsCompression(selectedFormat) && quality < 100) ? quality : null,
            width: elements.width.value ? parseSizeValue(elements.width.value) : null,
            height: elements.height.value ? parseSizeValue(elements.height.value) : null,
            maintainAspectRatio: elements.maintainAspectRatio.checked,
            // 添加裁剪选项
            crop: getCropOptions()
        };
        
        // 开始处理，使用默认的image文件夹作为输出目录
        const results = await ipcRenderer.invoke('process-images', {
            files: selectedFiles,
            outputFolder: 'image',
            options: options
        });
        
        // 计算耗时
        const processingTime = ((Date.now() - processingStartTime) / 1000).toFixed(1);
        
        // 显示完成提示框
        showCompletionModal(selectedFiles.length, processingTime, results);
        
    } catch (error) {
        showNotification('处理失败: ' + error.message, 'error');
    } finally {
        isProcessing = false;
        updateUI();
        elements.progressSection.style.display = 'none';
    }
}

// 处理进度更新
function handleProcessingProgress(event, progress) {
    const percent = Math.round((progress.current / progress.total) * 100);
    
    elements.progressText.textContent = `正在处理: ${progress.fileName} (${progress.current}/${progress.total})`;
    elements.progressPercent.textContent = `${percent}%`;
    elements.progressFill.style.width = `${percent}%`;
}

// 显示完成提示框
function showCompletionModal(fileCount, processingTime, results) {
    // 更新提示信息
    elements.completionMessage.textContent = `${fileCount}张图片已转换完成，耗时${processingTime}秒`;
    
    // 存储结果数据供按钮使用
    window.processingResults = results;
    
    // 显示模态框
    const modal = new bootstrap.Modal(elements.completionModal);
    modal.show();
}

// 替换原文件
async function replaceOriginalFiles() {
    try {
        const result = await ipcRenderer.invoke('replace-original-files', window.processingResults);
        if (result.success) {
            showNotification('原文件已成功替换', 'success');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(elements.completionModal);
            modal.hide();
            // 重置应用
            resetApplication();
        } else {
            showNotification('替换原文件失败: ' + result.error, 'error');
        }
    } catch (error) {
        showNotification('替换原文件失败: ' + error.message, 'error');
    }
}

// 查看转换结果
function viewResults() {
    // 打开image文件夹
    require('electron').shell.openPath(path.join(process.cwd(), 'image'));
    
    // 关闭模态框
    const modal = bootstrap.Modal.getInstance(elements.completionModal);
    modal.hide();
    
    // 重置应用
    resetApplication();
}

// 打开输出文件夹
function openOutputFolder() {
    require('electron').shell.openPath('image');
}

// 清空所有文件
function clearAllFiles() {
    if (selectedFiles.length === 0) {
        showNotification('没有文件需要清空', 'info');
        return;
    }
    
    // 确认清空
    if (confirm(`确定要清空所有 ${selectedFiles.length} 个文件吗？`)) {
        selectedFiles = [];
        updateFileList();
        updateUI();
        showNotification('已清空所有文件', 'success');
        
        // 关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('fileListModal'));
        if (modal) {
            modal.hide();
        }
    }
}

// 重置应用
function resetApplication() {
    selectedFiles = [];
    
    // 重置格式选择为保持原格式
    document.getElementById('formatOriginal').checked = true;
    
    elements.quality.value = 100;
    elements.qualityValue.textContent = '100';
    elements.width.value = '';
    elements.height.value = '';
    elements.maintainAspectRatio.checked = true;
    
    // 更新压缩设置显示
    updateCompressionSettings();
    
    updateFileList();
    updateUI();
    
    elements.progressSection.style.display = 'none';
    
    showNotification('应用已重置', 'info');
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    // 添加样式
    Object.assign(notification.style, {
        position: 'fixed',
        top: '20px',
        right: '20px',
        padding: '12px 20px',
        borderRadius: '8px',
        color: 'white',
        fontWeight: '500',
        zIndex: '10000',
        maxWidth: '400px',
        wordWrap: 'break-word',
        boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
        transform: 'translateX(100%)',
        transition: 'transform 0.3s ease'
    });
    
    // 设置背景颜色
    const colors = {
        info: '#3498db',
        success: '#27ae60',
        warning: '#f39c12',
        error: '#e74c3c'
    };
    notification.style.background = colors[type] || colors.info;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// 全局函数，供HTML调用
window.removeFile = removeFile;